package _14_网络编程._2_TCP编程.多线程.非线程池;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 服务端
 */
public class Server {

    public static void main(String[] args) throws IOException {
        //指定端口6666监听，未指定IP，表示在计算机的所有网络上进行监听
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("server is running... ");

        for (;;){
            //表示每当有新的客户端连接进来后，就返回一个Socket实例
            //Socket实例用来和刚建立的客户端进行通信的
            //主线程的作用是接收新的连接，每当收到新连接后，就创建一个新线程进行处理
            //如果没有客户端连接，accept()方法会阻塞并一直等待。
            //如果有多个客户端同时连接进来，ServerSocket会把连接扔到队列里，然后一个个处理。
            //对于Java程序而言，只需要通过循环不断调用accept()就可以获取新的连接。
            Socket socket = serverSocket.accept();
            System.out.println("connected from " + socket.getRemoteSocketAddress());
            //由于客户端很多，需要实现并发处理，必须为每个新的Socket创建一个新线程
            Thread thread = new Handler(socket);
            thread.start();
        }

    }

    static class Handler extends Thread{
        Socket socket;

        public Handler(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run(){
            try(InputStream inputStream = this.socket.getInputStream()){
                try(OutputStream outputStream = this.socket.getOutputStream()){
                    handle(inputStream, outputStream);
                }
            }
            catch(Exception e){
                e.printStackTrace();
            }
            finally {
                try {
                    this.socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        private void handle(InputStream inputStream, OutputStream outputStream) throws IOException {
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,StandardCharsets.UTF_8));

            bufferedWriter.write("hello \n");
            bufferedWriter.flush();

            for(;;){
                String string = bufferedReader.readLine();
                if(string.equals("bye")){
                    bufferedWriter.write("bye\n");
                    bufferedWriter.flush();
                    break;
                }
                bufferedWriter.write("ok " + string + "\n");
                bufferedWriter.flush();
            }
        }

    }
}

